#include "preHeader.h"
#include "CenterSession.h"
#include "CenterSessionHandler.h"
#include "ServerMaster.h"
#include "GateServer.h"
#include "network/ConnectionManager.h"

CenterSession::CenterSession()
: RPCSession("CenterSession", SCT_RPC_INVOKE_RESP)
{
}

CenterSession::~CenterSession()
{
	for (auto pck : m_toSendPckList) {
		delete pck;
	}
}

void CenterSession::CheckConnection()
{
	const auto& connPrePtr = GetConnection();
	if (connPrePtr && connPrePtr->IsActive()) {
		return;
	}
	if (!IsStatus(Idle)) {
		return;
	}

	auto& cfg = IServerMaster::GetInstance().GetConfig();
	auto connPtr = sConnectionManager.NewConnection(*this);
	connPtr->AsyncConnect(
		cfg.GetString("CENTER_SERVER", "HOST", "127.0.0.1"),
		cfg.GetString("CENTER_SERVER", "PORT", "9800"));

	sSessionManager.AddSession(this);
}

void CenterSession::SendPacket(const INetPacket& pck)
{
	if (IsReady()) {
		PushSendPacket(pck);
	} else {
		m_toSendPckList.push_back(pck.Clone());
	}
}

int CenterSession::HandlePacket(INetPacket *pck)
{
	return sCenterSessionHandler.HandlePacket(this, *pck);
}

void CenterSession::OnConnected()
{
	NetPacket req(CCT_REGISTER);
	PushSendPacket(req);
	RPCSession::OnConnected();
}

void CenterSession::OnShutdownSession()
{
	WLOG("Close CenterSession.");
	Session::OnShutdownSession();
}

void CenterSession::DeleteObject()
{
	ClearRecvPacket();
	ClearShutdownFlag();
	SetStatus(Idle);
}

int CenterSessionHandler::HandleRegisterResp(CenterSession *pSession, INetPacket &pck)
{
	int32 errCode;
	std::string_view errMsg;
	pck >> errCode >> errMsg;
	if (errCode != 0) {
		WLOG("Center Session Resp message[%u] %.*s.\n",
			pck.GetOpcode(), int(errMsg.size()), errMsg.data());
		return SessionHandleKill;
	}

	pSession->OnRPCSessionReady();

	for (auto pck : pSession->m_toSendPckList) {
		pSession->PushSendPacket(*pck);
		delete pck;
	}
	pSession->m_toSendPckList.clear();

	NLOG("Register to CenterServer Success.");

	return SessionHandleSuccess;
}
